package com.example.finance_manager.pages;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.finance_manager.GLOBAL;
import com.example.finance_manager.R;
import com.example.finance_manager.dao.UserDao;
import com.example.finance_manager.models.User;

import java.util.List;

public class SystemSettingActivity extends AppCompatActivity {

    private EditText etOldPwd;
    private EditText etNewPwd;
    private EditText etRePwd;
    private Button btnUpdate;
    private Button btnCancel;
    private UserDao userDao;
    private List<User> username;
    private String oldPwd;
    private String newPwd;
    private String rePwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_setting);

        userDao = new UserDao(this);
        initView();
        initListener();
    }

    private void initView() {
        etOldPwd = findViewById(R.id.et_setting_old_password);
        etNewPwd = findViewById(R.id.et_setting_new_password);
        etRePwd = findViewById(R.id.et_setting_re_password);

        btnUpdate = findViewById(R.id.btn_setting_update);
        btnCancel = findViewById(R.id.btn_setting_cancel);

    }

    private void initData() {
        oldPwd = etOldPwd.getText().toString();
        newPwd = etNewPwd.getText().toString();
        rePwd = etRePwd.getText().toString();
    }

    private void initListener() {
        btnUpdate.setOnClickListener(view -> {
            User user = userDao.findByUsername(GLOBAL.username).get(0);
            initData();
            if (!user.getPassword().equals(oldPwd)) {
                showToast("原密码错误！");
            } else if (!newPwd.equals(rePwd)) {
                showToast("新密码与确认密码不同！");
            } else {
                userDao.update(new User(GLOBAL.username, newPwd));
                showToast("密码修改成功！");
            }
        });
        btnCancel.setOnClickListener(view -> {
            finish();
        });
    }

    private void showToast(String text) {
        Toast.makeText(SystemSettingActivity.this, text, Toast.LENGTH_LONG).show();
    }
}